use crate::models::product_translations::{self, CreateParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/product-translations", post(create))
        .route("/product-translations/:id", get(get_by_id))
        .route("/product-translations/:id", post(update))
        .route("/product-translations/:id/delete", post(delete))
        .route(
            "/product-translations/by-product/:product_id",
            get(get_by_product),
        )
        .route(
            "/product-translations/by-product/:product_id/locale/:locale",
            get(get_by_product_and_locale),
        )
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let product_translation = product_translations::Model::create(&state.db, &params).await?;
    format::json(product_translation)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let product_translation = product_translations::Model::find_by_id(&state.db, &id).await?;
    format::json(product_translation)
}

async fn update(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let product_translation = product_translations::Model::find_by_id(&state.db, &id).await?;
    let active_model: product_translations::ActiveModel = product_translation.into();



    format::json(())
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let product_translation = product_translations::Model::find_by_id(&state.db, &id).await?;
    product_translation.delete(&state.db).await?;
    format::json(())
}

async fn get_by_product(
    State(state): State<AppContext>,
    axum::extract::Path(product_id): axum::extract::Path<String>,
) -> Result<Response> {
    let product_translations =
        product_translations::Model::find_by_product_id(&state.db, &product_id).await?;
    format::json(product_translations)
}

async fn get_by_product_and_locale(
    State(state): State<AppContext>,
    axum::extract::Path((product_id, locale)): axum::extract::Path<(String, String)>,
) -> Result<Response> {
    let product_translation =
        product_translations::Model::find_by_product_id_and_locale(&state.db, &product_id, &locale)
            .await?;
    format::json(product_translation)
}
